package com.cyandpos.pad.utils.log;

import android.os.Environment;

import com.cyandpos.pad.common.commondata.ErpCommonData;
import com.cyandpos.pad.pickhangup.SaveHangUpCallBack;
import com.cyandpos.pad.posdata.O2OPayDetail;
import com.cyandpos.pad.posdata.TicketInfo;
import com.cyandpos.pad.utils.CommonUtils;
import com.cyandpos.pad.utils.PubData;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Administrator on 2017/4/25.
 */

public class SDTools {

    private static String LOCAL_LOG_NAME = "ChangYiBusiness";
    public static final String PICK_TRADE = "pickTrade";    //取单
    public static final String CLASSIFY = "classify";       //取单

    /**
     * 把小票写到文件中(已经写到了线程中)
     * @param ticket 小票
     */
    public static void writeTicket(TicketInfo ticket) {
        if (ticket == null || !CommonUtils.isSdcardReady()) {
            return;
        }
        final String ticketId = ticket.getOrderNo();
        final String json = PubData.GSON.toJson(ticket);
        new Thread() {
            public void run() {
                BufferedWriter bfWriter = null;
                try {
                    File dir = new File( PubData.SD_ROOT_PATH
                            + File.separator + PubData.FILE_ROOT_NAME
                            + File.separator + PubData.FILE_PROJECT_NAME
                            + File.separator + PubData.FILE_TICKET_NAME

                    );


                    if (!dir.exists())
                        dir.mkdirs();
                    File file = new File(dir + File.separator + "XSJL" + ticketId);
                    bfWriter = new BufferedWriter(new FileWriter(file));
                    bfWriter.write(json);
                    bfWriter.flush();
                    bfWriter.close();
                } catch (Exception e) {
                    MessageLog.writeLog("写本地小票异常 :" + ticketId);
                    bfWriter = null;
                }
            }
        }.start();
    }

    /**
     * 读取小票文件
     * @param ticketId 记录编号
     * @return 小票
     */
    public static TicketInfo readTicket(int ticketId) {
        if (ticketId <= 0 || !CommonUtils.isSdcardReady())
            return null;
        BufferedReader bfReader = null;
        try {
            File dir = new File(
                    PubData.SD_ROOT_PATH
                            + File.separator + PubData.FILE_ROOT_NAME
                            + File.separator + PubData.FILE_PROJECT_NAME
                            + File.separator + PubData.FILE_TICKET_NAME
            );
            if (!dir.exists())
                dir.mkdirs();

            File file = new File(dir + File.separator + "XSJL" + ticketId);
            if (file.exists()) {
                bfReader = new BufferedReader(new FileReader(file));
                TicketInfo ticket = PubData.GSON.fromJson(bfReader, TicketInfo.class);
                bfReader.close();
                return ticket;
            } else {
                return null;
            }
        } catch (Exception e) {
            bfReader = null;
            MessageLog.writeLog("读取小票异常 :" + ticketId);
            return null;
        }
    }

    public static void writeO2OTicket(O2OPayDetail wxTicket, final int flag) {
        //flag =1 微信   flag =2 支付宝   flag =3 礼品券
        if (wxTicket == null || !CommonUtils.isSdcardReady()) {
            return;
        }
        final String transactionId = wxTicket.getJlbh()+"";
        final String json = PubData.GSON.toJson(wxTicket);
        new Thread() {
            public void run() {
                BufferedWriter bfWriter = null;
                try {
                    File dir = new File( PubData.SD_ROOT_PATH
                            + File.separator + PubData.FILE_ROOT_NAME
                            + File.separator + PubData.FILE_PROJECT_NAME
                            + File.separator + PubData.FILE_TICKET_NAME
                    );

                    if (!dir.exists())
                        dir.mkdirs();
                    File file = null;
                    if(flag == 1){
                        file = new File(dir + File.separator + "WXJL" + transactionId);
                    }else if(flag == 2){
                        file = new File(dir + File.separator + "ZFBJL" + transactionId);
                    }else if(flag == 3){
                        file = new File(dir + File.separator + "LPQJL" + transactionId);
                    }else if(flag == 4){
                        file = new File(dir + File.separator + "JHJL" + transactionId);
                    }
                    bfWriter = new BufferedWriter(new FileWriter(file));
                    bfWriter.write(json);
                    bfWriter.flush();
                    bfWriter.close();
                } catch (Exception e) {
                    if(flag == 1)
                        MessageLog.writeLog("写本地微信小票异常 :" + transactionId);
                    else if(flag == 2)
                        MessageLog.writeLog("写本地支付宝小票异常 :" + transactionId);
                    else if(flag == 3)
                        MessageLog.writeLog("写本地礼品券小票异常 :" + transactionId);
                    else if(flag == 4)
                        MessageLog.writeLog("写本地聚合小票异常 :" + transactionId);
                    bfWriter = null;
                }
            }
        }.start();
    }

    public static O2OPayDetail readO2OTicket(String transactionId, int flag ) {
        if (transactionId.equals("") || !CommonUtils.isSdcardReady())
            return null;
        BufferedReader bfReader = null;
        try {

            File dir = new File( PubData.SD_ROOT_PATH
                    + File.separator + PubData.FILE_ROOT_NAME
                    + File.separator + PubData.FILE_PROJECT_NAME
                    + File.separator + PubData.FILE_TICKET_NAME
            );
            if (!dir.exists())
                dir.mkdir();

            File file = null;
            if(flag == 1){
                file = new File(dir + File.separator + "WXJL" + transactionId);
            }else if(flag == 2){
                file = new File(dir + File.separator + "ZFBJL" + transactionId);
            }else if(flag == 3){ //flag =3 礼品券
                file = new File(dir + File.separator + "LPQJL" + transactionId);
            }else if(flag == 4){ //flag =3 聚合支付
                file = new File(dir + File.separator + "JHJL" + transactionId);
            }
            if (file.exists()) {
                bfReader = new BufferedReader(new FileReader(file));
                O2OPayDetail ticket = PubData.GSON.fromJson(bfReader, O2OPayDetail.class);
                bfReader.close();
                return ticket;
            } else {
                return null;
            }
        } catch (Exception e) {
            bfReader = null;
            if(flag == 1)
                MessageLog.writeLog("读取微信小票异常 :" + transactionId);
            else if(flag == 2)
                MessageLog.writeLog("读取支付宝小票异常 :" + transactionId);
            else if(flag == 3)
                MessageLog.writeLog("读取礼品券小票异常 :" + transactionId);
            else if(flag == 4)
                MessageLog.writeLog("读取聚合小票异常 :" + transactionId);
            return null;
        }
    }

    /**
     * 挂单
     * 把小票写到文件中
     * @param ticket 小票
     */
    public static void writeTicketPick(TicketInfo ticket, final String code, final SaveHangUpCallBack callBack) {
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss:SSS");
        java.text.SimpleDateFormat f = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        final String str = "_" + f.format(curDate);
        if (ticket == null) {
            callBack.onFailed("小票为空");
        }
        if (!CommonUtils.isSdcardReady()) {
            callBack.onFailed("内存卡异常");
        }
        final String json = PubData.GSON.toJson(ticket);
        new Thread() {
            public void run() {
                BufferedWriter bfWriter;
                try {
                    File dir = new File(Environment
                            .getExternalStorageDirectory().getPath()
                            + File.separator + LOCAL_LOG_NAME
                            + File.separator + PICK_TRADE);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                    File file = new File(dir + File.separator + ErpCommonData.sktno + "_" + code + str);
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    bfWriter = new BufferedWriter(new FileWriter(file));
                    bfWriter.write(json);
                    bfWriter.flush();
                    bfWriter.close();
                } catch (Exception e) {
                    callBack.onFailed(e.getMessage());
                    System.out.println("写小票异常" + e);
                }
            }
        }.start();
        callBack.onSuccess(f.format(curDate));
    }

    /**
     * 读取挂单小票文件
     *
     * @return 小票
     */
    public static TicketInfo readTicketPick(String path) {
        if (!CommonUtils.isSdcardReady())
            return null;
        BufferedReader bfReader;
        try {

            File file = new File(path);
            bfReader = new BufferedReader(new FileReader(file));
            TicketInfo ticket =PubData.GSON.fromJson(bfReader, TicketInfo.class);
            bfReader.close();
            return ticket;
        } catch (Exception e) {
            System.out.println("读取小票文件异常：" + e);
            return null;
        }
    }

    /**
     * 删除挂单小票文件
     *
     * @return 小票
     */
    public static void deleteTicketPick(String path) {
        if (!CommonUtils.isSdcardReady())
            return;
        try {
            File file = new File(path);
            file.delete();
        } catch (Exception e) {
            System.out.println("读取小票文件异常：" + e);
        }
    }


    /**
     * 遍历取单文件
     */
    public static List<String> traverseFolderPick() {
        List<String> arr = new ArrayList<>();
        File dir = new File(Environment.getExternalStorageDirectory().getPath()
                + File.separator + LOCAL_LOG_NAME
                + File.separator + PICK_TRADE);
        int fileNum = 0, folderNum = 0;
        File file = dir;
        if (file.exists()) {
            LinkedList<File> list = new LinkedList<>();
            File[] files = file.listFiles();
            for (File file2 : files) {
                if (file2.isDirectory()) {
                    list.add(file2);
                    folderNum++;
                } else {
                    arr.add(file2.getAbsolutePath());
                    fileNum++;
                }
            }
            File temp_file;
            while (!list.isEmpty()) {
                temp_file = list.removeFirst();
                files = temp_file.listFiles();
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        list.add(file2);
                        folderNum++;
                    } else {
                        fileNum++;
                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
        System.out.println("文件夹共有:" + folderNum + ",文件共有:" + fileNum);
        return arr;
    }


}
